/*
 * Created by IntelliJ IDEA.
 * User: jbirchfield
 * Date: Mar 19, 2002
 * Time: 9:33:22 AM
 */

import com.sun.crypto.provider.SunJCE;

import javax.crypto.KeyGenerator;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

public class KeyGen {

    public static final String KEY_FILE = "secret.key";
    public static final String ALGORITHM = "DES";

    public static void main(String[] args) {
        Security.addProvider(new SunJCE());
        new KeyGen();
    }

    public KeyGen() {
        KeyGenerator kg = null;
        try {
            kg = KeyGenerator.getInstance(ALGORITHM);
            Key key = kg.generateKey();
            writeKey(KEY_FILE, key);
        }
        catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    private void writeKey(String filename, Object o) {
        try {
            FileOutputStream fos = new FileOutputStream(filename);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(o);
            oos.flush();
            fos.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Key getSecretKey() {
        Security.addProvider(new SunJCE());
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(KEY_FILE);
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Key key = null;

        try {
            ObjectInputStream ois = null;
            ois = new ObjectInputStream(fis);
            key = null;
            key = (Key) ois.readObject();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        System.out.println("key = " + key);
        return key;
    }
}

